package com.example.zhunongzonghe.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zhunongzonghe.beans.ZnPostLikeBean;
import com.example.zhunongzonghe.dao.ZnPostLikeMapper;
import com.example.zhunongzonghe.dao.ZnUsersMapper;
import com.example.zhunongzonghe.entity.ZnPostLike;
import com.example.zhunongzonghe.entity.ZnUsers;
import com.example.zhunongzonghe.enums.PostLikeStatusEnum;
import com.example.zhunongzonghe.service.ZnPostLikeService;
import com.example.zhunongzonghe.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
* @author 蔡某人
* @description 针对表【zn_post_like】的数据库操作Service实现
* @createDate 2024-04-03 19:16:28
*/
@Service
public class ZnPostLikeServiceImpl extends ServiceImpl<ZnPostLikeMapper, ZnPostLike>
    implements ZnPostLikeService{

    @Resource
    private RedisCache redisCache;
    @Autowired
    ZnUsersMapper znUsersMapper;
    @Autowired
    private ZnPostLikeMapper znPostLikeMapper;
    private static final String POST_LIKE_KEY = "post_like";//hash前缀
    private static final String POST_LIKE_COUNT_KEY = "post_like_count";//hash前缀
    private static final String POST_LIKE_DETAIL_KEY = "post_like_detail";//hash前缀
    /**
     *用户点赞评价
     * @param znPostLikeBean
     */
    @Override
    public void addLike(ZnPostLikeBean znPostLikeBean,String UserName) {
        LambdaQueryWrapper<ZnUsers> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnUsers::getUserName,UserName);
        ZnUsers znUsers = znUsersMapper.selectOne(queryWrapper);
        Integer postId = znPostLikeBean.getPostId();
        Integer userId = znUsers.getId();
        Integer status = znPostLikeBean.getLikeStatus();
        //与redis做交互的Hash的key
        String likeHashKey = buildPostLikeKey(postId.toString(),userId.toString());
        redisCache.setCacheHashValue(POST_LIKE_KEY,likeHashKey,status);
        String detailKey = POST_LIKE_DETAIL_KEY+"."+postId+"."+userId;//被谁点过赞的key
        String countKey = POST_LIKE_COUNT_KEY+"."+postId;
        if (PostLikeStatusEnum.LIKED.getCode() == status){
            redisCache.increment(countKey,1);//点赞时加1
            redisCache.setCacheObject(detailKey,"1");
        }else {
            Integer count =redisCache.getInt(countKey);
            if (Objects.isNull(count) || count<0){
                return;
            }
            redisCache.increment(countKey,-1);//取消点赞时-1
            redisCache.deleteObject(detailKey);
        }

    }

    /**
     * 是否点过赞
     * @param postId
     * @param userId
     * @return
     */
    @Override
    public Boolean isLiked(Integer postId, Integer userId) {
        String detailKey = POST_LIKE_DETAIL_KEY+"."+postId+"."+userId;//被谁点过赞的key
        return redisCache.exist(detailKey);//获取redis内的detailKey，如果存在说明当前用户点赞过该帖子
    }

    /**
     * 点赞总数量
     * @param postId
     * @return
     */
    @Override
    public Integer likeCounts(Integer postId) {
        String countKey = POST_LIKE_COUNT_KEY+"."+postId;
        Integer count =redisCache.getInt(countKey);
        if (Objects.isNull(count) || count<0){
            return 0;
        }
        return redisCache.getInt(countKey);
    }

    @Override
    public void syncPostLiked() {
        Map<Object,Object> postLikeMap = redisCache.getHashAndDelete(POST_LIKE_KEY);
        if (MapUtil.isEmpty(postLikeMap)){
            return;
        }
        //批量同步到数据库
        List<ZnPostLike> znPostLikes = new ArrayList<>();
        postLikeMap.forEach((key,value) ->{
            ZnPostLike znPostLike = new ZnPostLike();
            String[] keyArr = key.toString().split(":");
            String postId = keyArr[0];
            String UserId = keyArr[1];
            znPostLike.setPostId(Integer.valueOf(postId));
            znPostLike.setUserId(Integer.valueOf(UserId));
            znPostLike.setLikeStatus((Integer) value);
            znPostLike.setCreateTime(LocalDateTime.now());
            znPostLike.setUpdateTime(LocalDateTime.now());
            znPostLikes.add(znPostLike);
        });
        znPostLikeMapper.insertList(znPostLikes);

    }

    private String buildPostLikeKey(String postId,String userId){
        return postId + ":" +userId;
    }
}




